package com.csgc.camera.biz.other.activity

import android.content.Context
import android.content.Intent
import android.os.Bundle
import android.text.Editable
import android.text.TextWatcher
import android.view.MotionEvent
import android.view.View
import androidx.recyclerview.widget.LinearLayoutManager
import com.amap.api.location.AMapLocationClient
import com.amap.api.location.AMapLocationClientOption
import com.amap.api.location.AMapLocationListener
import com.amap.api.services.core.LatLonPoint
import com.amap.api.services.core.PoiItemV2
import com.amap.api.services.poisearch.PoiResultV2
import com.amap.api.services.poisearch.PoiSearchV2
import com.csgc.camera.base.BaseBindingActivity
import com.csgc.camera.bean.LocationInfo
import com.csgc.camera.bean.LocationTabState
import com.csgc.camera.biz.other.adapter.LocationSelectAdapter
import com.csgc.camera.constants.MaskConfig
import com.csgc.camera.events.MaskLocationEvent
import com.csgc.camera.util.clickWithTrigger
import com.cysd.spsyxj.R
import com.cysd.spsyxj.databinding.ActivityLocationSelectBinding
import com.drake.channel.sendEvent
import com.elvishew.xlog.XLog
import com.gyf.immersionbar.ktx.immersionBar
import com.hjq.toast.ToastUtils
import com.hlyj.http.ad.NewGroMoreFeedAdManager
import com.hnyyac.ad.mds.IAdView
import com.hnyyac.ad.mds.IAdViewListener
import com.hnyyac.ad.mds.manager.AdManager
import com.hnyyac.ad.mds.manager.AdManager.AdLoadListener
import com.hnyyac.ad.mds.utils.BaseAdConstants

class LocationSelectActivity :
    BaseBindingActivity<ActivityLocationSelectBinding>(ActivityLocationSelectBinding::inflate),
    IAdViewListener {


    companion object {
        private const val KEY_LOCATION_LAT = "location_lat"
        private const val KEY_LOCATION_LNG = "location_lng"
        private const val KEY_LOCATION_STREET = "location_street"
        fun launch(context: Context, lat: Double, lng: Double, street: String) {
            val intent = Intent(context, LocationSelectActivity::class.java)
            intent.putExtra(KEY_LOCATION_LAT, lat)
            intent.putExtra(KEY_LOCATION_LNG, lng)
            intent.putExtra(KEY_LOCATION_STREET, street)
            context.startActivity(intent)
        }
    }

    private var locationLat: Double = 0.0
    private var locationLng: Double = 0.0
    private var locationType:Int = 0
    private var street: String = ""
    private val locationInfoList: ArrayList<LocationInfo> by lazy {
        ArrayList()
    }
    private var province = ""
    private var city = ""
    private var district = ""
    private var snippet = ""
    private val adapter: LocationSelectAdapter by lazy {
        val adapter = LocationSelectAdapter(this, locationInfoList)
        adapter.listener = object : LocationSelectAdapter.OnLocationSelectListener {
            override fun onSelect(snippet: String) {
                this@LocationSelectActivity.snippet = snippet

                MaskConfig.setLocationStyle(province, city, district, street, snippet)
                sendEvent(MaskLocationEvent(MaskConfig.maskLocation))
            }
        }
        adapter
    }

    private val mLocationClient: AMapLocationClient by lazy {
        AMapLocationClient(this)
    }
    private val mLocationListener: AMapLocationListener by lazy {
        AMapLocationListener {
            province = it.province
            city = it.city
            district = it.district
            street = it.street
            locationLat = it.latitude
            locationLng = it.longitude
            loadLocation()
        }
    }
    private val mLocationOption: AMapLocationClientOption by lazy {
        val option = AMapLocationClientOption()
        option.locationMode = AMapLocationClientOption.AMapLocationMode.Hight_Accuracy
        option.isOnceLocation = true
        option.isOnceLocationLatest = true
        option.isNeedAddress = true
        option
    }

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        immersionBar {
            fitsSystemWindows(true)
            statusBarColor(R.color.f1f1f1)
            statusBarDarkFont(false)
        }

        street = intent.getStringExtra(KEY_LOCATION_STREET) ?: ""
        locationLat = intent.getDoubleExtra(KEY_LOCATION_LAT, 0.0)
        locationLng = intent.getDoubleExtra(KEY_LOCATION_LNG, 0.0)

        initView()
        if (street.isEmpty()) {
            startLocation()
        } else {
            loadLocation()
        }

        initData()
        initListener()

    }

    private fun initListener() {
        binding.myLocationText.clickWithTrigger {
            switchLocation(1)
        }
        binding.nearbyLocationText.clickWithTrigger {
            switchLocation(0)
        }
        binding.etSearch.addTextChangedListener(object : TextWatcher {
            override fun beforeTextChanged(
                p0: CharSequence?,
                p1: Int,
                p2: Int,
                p3: Int
            ) {

            }

            override fun onTextChanged(
                p0: CharSequence?,
                p1: Int,
                p2: Int,
                p3: Int
            ) {

            }

            override fun afterTextChanged(p0: Editable?) {
                searchLocation(p0.toString())
            }
        })

        binding.tvRefresh.clickWithTrigger {
              //判断如若是选择的1就load地址 判断二就搜索地址
            showLoading()

            when(locationType){
                0 -> {
                    // 处理附近位置(Nearby)的逻辑
                    loadLocation()
                }
                1 -> {
                    // 处理自定义位置(Custom)的逻辑
                    searchLocation(binding.etSearch.text.toString())
                }
            }
        }


        // 设置右侧清除按钮的点击事件
        binding.etSearch.setOnTouchListener { _, event ->
            if (event.action == MotionEvent.ACTION_UP) {
                // 判断点击位置是否在右侧drawable上
                val drawableRight = binding.etSearch.compoundDrawables[2] // 右侧drawable
                if (drawableRight != null &&
                    event.rawX >= (binding.etSearch.right - drawableRight.bounds.width())) {
                    // 清除输入框内容
                    binding.etSearch.setText("")
                    return@setOnTouchListener true
                }
            }
            false
        }
    }



    private fun initData() {
        //广告插入
        val newGromoreFeedAd: NewGroMoreFeedAdManager =
            NewGroMoreFeedAdManager(this, BaseAdConstants.FEEDAD_Id, binding?.frameContent, 66)
        newGromoreFeedAd.loadAd()
        showDoubleChaPin()
    }

    private fun switchLocation(type: Int) {
        locationType = type
        val states = mapOf(
            1 to LocationTabState(true, View.VISIBLE),
            0 to LocationTabState(false, View.GONE)
        )

        states[type]?.let { state ->
            binding.myLocationText.isSelected = state.isSelected
            binding.nearbyLocationText.isSelected = !state.isSelected
            binding.etSearch.visibility = state.searchVisibility

            if (type == 1) clearAdapterData() else loadLocation()
        }
    }


    private fun initView() {
        binding.ivBack.clickWithTrigger {
            finish()
        }

        binding.rvLocationList.layoutManager =
            LinearLayoutManager(this, LinearLayoutManager.VERTICAL, false)
        binding.rvLocationList.adapter = adapter

        binding.layoutSettingLocationStyle.clickWithTrigger {
            if (snippet.isNotEmpty()) {
                LocationStyleActivity.launch(this, province, city, district, street, snippet)
            }

        }

        binding.nearbyLocationText.isSelected = true
        binding.myLocationText.isSelected = false
    }

    //清空 数据
    // 直接操作 RecyclerView 的 adapter
    private fun clearAdapterData() {
        with(adapter) {
            list.clear()
            notifyDataSetChanged()
        }
    }


    private fun startLocation() {
        mLocationClient.setLocationOption(mLocationOption)
        mLocationClient.setLocationListener(mLocationListener)
        mLocationClient.startLocation()
    }


    //新增一个根据文字搜索地图的方法
    //新增一个根据文字搜索地图的方法
    private fun searchLocation(keyword: String) {
        // 创建查询条件
        val query = PoiSearchV2.Query(keyword, "", city)
        query.pageSize = 20
        query.pageNum = 1

        // 创建POI搜索对象
        val poiSearch = PoiSearchV2(this, query)

        // 设置搜索边界，以当前位置为中心点
//        val bound = PoiSearchV2.SearchBound(LatLonPoint(locationLat, locationLng), 5000)
//        poiSearch.bound = bound

        // 设置搜索监听器
        poiSearch.setOnPoiSearchListener(object : PoiSearchV2.OnPoiSearchListener {
            override fun onPoiSearched(result: PoiResultV2?, errorCode: Int) {
                if (errorCode == 1000 && result != null) {
                    locationInfoList.clear()
                    result.pois?.forEach { poiItem ->
                        val info = LocationInfo(
                            poiItem.provinceName,
                            poiItem.cityName,
                            poiItem.adName,
                            poiItem.title,
                            poiItem.snippet
                        )
                        locationInfoList.add(info)
                    }
                    adapter.notifyDataSetChanged()
                    binding.tvAddress.text =
                        "${locationInfoList.firstOrNull()?.province ?: ""}${locationInfoList.firstOrNull()?.city ?: ""}${locationInfoList.firstOrNull()?.district ?: ""}${locationInfoList.firstOrNull()?.street ?: ""}"

                    binding.root.postDelayed({
                        hideLoading()
                        ToastUtils.show("刷新成功")
                    }, 2000 )
                }
            }

            override fun onPoiItemSearched(poiItem: PoiItemV2?, errorCode: Int) {
                // 单个POI项搜索结果回调
            }
        })

        // 发起异步搜索
        poiSearch.searchPOIAsyn()
    }

    private fun loadLocation() {
        val bound = PoiSearchV2.SearchBound(LatLonPoint(locationLat, locationLng), 1000, true)

        val query = PoiSearchV2.Query("", "", "")
        query.pageSize = 20
        query.pageNum = 1
        val poiSearchV2 = PoiSearchV2(this, query)
        poiSearchV2.bound = bound
        poiSearchV2.setOnPoiSearchListener(object : PoiSearchV2.OnPoiSearchListener {
            override fun onPoiSearched(p0: PoiResultV2?, p1: Int) {
                locationInfoList.clear()
                p0?.pois?.forEach {
                    if (province.isEmpty()) {
                        province = it.provinceName
                    }
                    if (city.isEmpty()) {
                        city = it.cityName
                    }
                    if (district.isEmpty()) {
                        district = it.adName
                    }
                    if (snippet.isEmpty()) {
                        snippet = it.snippet
                    }

                    val info =
                        LocationInfo(it.provinceName, it.cityName, it.adName, street, it.snippet)
                    locationInfoList.add(info)
                    binding.tvAddress.text =
                        locationInfoList.first()?.city + locationInfoList.first()?.district + locationInfoList.first()?.street
                    adapter.notifyDataSetChanged()

                    XLog.e("=====poi${it.provinceName}")
                    XLog.e("=====poi${it.cityName}")
                    //岳麓区
                    XLog.e("=====poi${it.adName}")
                    //上面添加街道

                    XLog.e("=====poi${it.snippet}")
                    // 延迟2秒隐藏加载对话框
                    binding.root.postDelayed({
                        hideLoading()
                        ToastUtils.show("刷新成功")
                    }, 2000 )
                }
            }

            override fun onPoiItemSearched(p0: PoiItemV2?, p1: Int) {

            }
        })
        poiSearchV2.searchPOIAsyn()
    }

    override fun onDestroy() {
        super.onDestroy()
        mLocationClient.stopLocation()
        mLocationClient.onDestroy()
    }

    //统一双插屏无需加位置
    fun showDoubleChaPin() {
        AdManager.loadTwoChapinSimultaneously(
            this,
            666,
            this,
            object : AdLoadListener {
                override fun onAdLoadFailed(ad: IAdView?) {

                }
            })
    }

    override fun onTrigger(adView: IAdView) {

    }

    override fun onAdShow(adView: IAdView) {

    }

    override fun onAdClick(adView: IAdView) {

    }

    override fun onAdClose(adView: IAdView) {

    }

    override fun onError(msg: String) {

    }

    override fun onLoadError(adView: IAdView) {

    }

    override fun onSuccess(adView: IAdView) {

    }

    override fun onLoad(adView: IAdView) {

    }

    override fun onSkipped() {

    }

    override fun onNoAd() {

    }

    override fun onTimeOut() {

    }
}